<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 添加接口
 *
 * @author      Eden
 * @datetime    2016/12/1 22:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class More_Model extends API_Model
{

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run(Array $params)
    {
        $send['state'] = false;
        do {

            if (empty($params['userId']) || empty($params['orderId'])) {
                $send['error'] = '参数错误';
                break;
            }

            $goods = $this->getGoods($params['orderId']);
            if (empty($goods)) {
                $send['error'] = '商品不存在';
                break;
            }

            $db = clone($this->db);
            $db->where('userid', $params['userId']);
            $db->update('user_car', ['selected' => 0]);

            foreach($goods as $item) {

                $where = [
                    'userId' => $params['userId'],
                    'goodsId' => $item['goodsId'],
                    'ruleId' => $item['ruleId']
                ];

                $db2 = clone($this->db);
                $db2->where($where);
                $q2 = $db2->get('user_car');
                $row = $q2->row_array();

                $db3 = clone($this->db);
                if (!empty($row)) {
                    $db3->where($where);
                    $db3->update('user_car', [
                        'selected' => 1,
                        'num' => $item['num']
                    ]);
                } else {
                    $db3->insert('user_car', [
                        'userId' => $params['userId'],
                        'goodsId' => $item['goodsId'],
                        'num' => $item['num'],
                        'created' => date('Y-m-d H:i:s'),
                        'selected' => 1,
                        'ruleId' => $item['ruleId']
                    ]);
                }
            }

            $send['state'] = true;
            $send['data'] = [
                'msg' => '操作成功'
            ];

        } while (false);
        $this->output->send($send);
    }

    /**
     * @param $orderId
     * @return mixed
     */
    private function getGoods($orderId)
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order_goods', ['orderId' => $orderId]);
        return $q->result_array();
    }
}
